/**
 * 
 */
package com.iot.ic.utils;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author DaYong.Shen
 *
 */
public class FileUtil implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;

	private static Logger logger= LoggerFactory.getLogger(FileUtil.class);
	// System.getProperty( "line.separator" )
	/**
	 * 文本文件所在的目录
	 */
	private static String textPath = System.getProperty("user.dir") + File.separator + "data";
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
	}
	
	public static void getResource() throws IOException{
		Resource resource=applicationContext.getResource("classpath:spring.xml");
		logger.info(resource.getFilename());
		logger.info("长度"+resource.contentLength());
	}

	/**
	 * 读取文本内容
	 * 
	 * @param textname
	 *            文本名称
	 * @return
	 */
	public static String readText(String textname) {
		File file = new File(textPath + File.separator + textname);
		try {
			BufferedReader br = new BufferedReader(new java.io.FileReader(file));
			StringBuilder sb = new StringBuilder();
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			br.close();
			return sb.toString();
		} catch (IOException e) {
			logger.error("readText ERROR!" + e.getMessage());
			return null;
		}
	}

	/**
	 * 将内容写到文本中
	 * 
	 * @param textname
	 *            文本名称
	 * @param data
	 *            写入的内容
	 * @return
	 */
	public static boolean writeText(String textname, String data) {
		boolean flag = false;
		File filePath = new File(textPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		try {
			FileWriter fw = new FileWriter(textPath + File.separator + textname);
			fw.write(data + System.getProperty("line.separator"));
			flag = true;
			if (fw != null)
				fw.close();
		} catch (IOException e) {
			logger.error("writeText ERROR!" + e.getMessage());
		}
		return flag;
	}

	/**
	 * 在文档后附加内容
	 * 
	 * @param fileName
	 * @param content
	 * @return
	 */
	public static boolean appendText(String fileName, String content) {
		boolean flag = false;
		File filePath = new File(textPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		try {
			FileWriter fw = new FileWriter(textPath + File.separator + fileName, true);
			fw.append(content);
			flag = true;
			if (fw != null)
				fw.close();
		} catch (IOException e) {
			logger.error("appendText ERROR!" + e.getMessage());
		}
		return flag;
	}

	/**
	 * <p>Title: isExsit</p> <p>Description: </p>
	 *
	 * @param @param filepath 文件路径 @param @return 文件是否存在 @return Boolean @throws
	 */
	public static Boolean isExsit(String filepath) {
		File file = new File(filepath);
		return file.exists() && file.isFile();
	}

	public String getTextPath() {
		return textPath;
	}

	public void setTextPath(String textPath) {
		textPath = textPath;
	}

	/*
	 * 通过递归得到某一路径下所有的目录及其文件名
	 */
	public static List getFileNames(String filePath) {
		List<String> filelist = new ArrayList<String>();
		File root = new File(filePath);
		File[] files = root.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				/*
				 * 递归调用
				 */
				getFileNames(file.getAbsolutePath());
			} else {
				filelist.add(file.getAbsolutePath());
			}
		}
		return filelist;
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 *            上传文件
	 * @param location
	 *            上传存放路径
	 * @return
	 */
	public static String uploadFile(MultipartFile file, String location) {
		createDirIfNotEixt(location);
		String[] nameArr = file.getOriginalFilename().split("\\.");
		String fileName = "img_" + Math.round((Math.random() * 10000)) + System.currentTimeMillis() + "."
				+ nameArr[nameArr.length - 1];
		if (!file.isEmpty()) {
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(location, fileName));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return fileName;
		} else {
			return null;
		}
	}

	/**
	 * 将字符创保存为html文档
	 * 
	 * @param content
	 * @param location
	 * @return
	 */
	public static String saveHtml(String content, String location) {
		createDirIfNotEixt(location);
		String fileName = "course_" + Math.round((Math.random() * 10000)) + System.currentTimeMillis() + ".html";
		location = location + "\\" + fileName;
		FileWriter fwriter = null;
		try {
			File fp = new File(location);
			if (!fp.exists()) {
				fp.createNewFile();
			}
			fwriter = new FileWriter(fp);
			fwriter.write(content);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				fwriter.flush();
				fwriter.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return fileName;
	}
	
	/**
	 * 将字符创保存为html文档
	 * 
	 * @param content
	 * @param location
	 * @return
	 */
	public static boolean updateHtml(String content, String filePath) {
		FileWriter fwriter = null;
		try {
			File fp = new File(filePath);
			fwriter = new FileWriter(fp);
			fwriter.write(content);
		} catch (IOException ex) {
			return false;
		} finally {
			try {
				fwriter.flush();
				fwriter.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * 根据url活去html文档中的内容
	 * 
	 * @param urlString
	 * @return
	 */
	public static String getHtml(String urlString) {
		try {
			StringBuffer html = new StringBuffer();
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStreamReader isr = new InputStreamReader(conn.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			String temp;
			while ((temp = br.readLine()) != null) {
				html.append(temp).append("\n");
			}
			br.close();
			isr.close();
			return html.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据路径创建文件夹
	 * 
	 * @param path
	 */
	public static void createDirIfNotEixt(String path) {
		File file = new File(path);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
	}

	/**
	 * 根据路径创建文件
	 * 
	 * @param path
	 * @return
	 */
	public static boolean createFileIfNotEixt(String path) {
		File file = new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm");
		if (!file.exists()) {
			try {
				file.createNewFile();
				return true;
			} catch (IOException e) {
				return false;
			}
		}
		return false;
	}

	/**
	 * 更新图片文件
	 * 
	 * @param file
	 * @param location
	 * @return
	 */
	public static boolean updateFile(MultipartFile file, String location) {
		if (!file.isEmpty()) {
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(location));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 * @return
	 */
	public static boolean deleteFile(String path) {
		boolean flag = false;
		File file = new File(path);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
	
	public static byte[] readToBytes(String path) throws IOException{
		File file = new File(path);  
        long fileSize = file.length();  
        if (fileSize > Integer.MAX_VALUE) {  
            System.out.println("file too big...");  
            return null;  
        }  
        FileInputStream fi = new FileInputStream(file);  
        byte[] buffer = new byte[(int) fileSize];  
        int offset = 0;  
        int numRead = 0;  
        while (offset < buffer.length  
        && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {  
            offset += numRead;  
        }  
        // 确保所有数据均被读取  
        if (offset != buffer.length) {  
        throw new IOException("Could not completely read file "  
                    + file.getName());  
        }  
        fi.close();  
        return buffer; 
		
		
		
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileUtil.appendText("aisini.txt", "aisini");
		FileUtil.appendText("aisini.txt", "aisini");
		FileUtil.appendText("aisini.txt", "aisini");
	}

	

}
